package com.retoc.oawx.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retoc.oawx.domain.FaceModel;
import com.retoc.oawx.domain.MessageEntity;
import com.retoc.oawx.domain.User;
import com.retoc.oawx.exception.OAException;
import com.retoc.oawx.mapper.*;
import com.retoc.oawx.service.UserService;
import com.retoc.oawx.task.ActiveCodeTask;
import com.retoc.oawx.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author retoc
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2022-05-01 20:00:13
*/
@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private MessageTask messageTask;

    @Autowired
    private ActiveCodeTask activeCodeTask;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CheckinMapper checkinMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MessageRefMapper refMapper;

    @Autowired
    private FaceModelMapper faceModelMapper;

    private String getOpenId(String code){
        String url="https://api.weixin.qq.com/sns/jscode2session";
        HashMap map=new HashMap<>();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String resp = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(resp);
        String openid = json.getStr("openid");
        if (openid == null || openid.length() == 0) {
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openid;
    }

    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
        if (registerCode.equals("000000")){
            boolean b = userMapper.haveRootUser();
            if (!b) {
                String openId=getOpenId(code);
                HashMap param = new HashMap();
                param.put("openId", openId);
                param.put("nickname",nickname);
                param.put("photo", photo);
                param.put("role","[0]");
                param.put("status",1);
                param.put("createTime",new Date());
                param.put("root",true);
                userMapper.insertUser(param);
                int id=userMapper.searchIdByOpenId(openId);
                MessageEntity entity=new MessageEntity();
                entity.setSenderId(0);
                entity.setSenderName("系统消息");
                entity.setUuid(IdUtil.simpleUUID());
                entity.setMsg("欢迎注册超级管理员，请尽快更新您的个人信息");
                entity.setSendTime(new Date());
                messageTask.sendAsync(id+"",entity);
                return id;
            }else {
                throw new OAException("无法绑定超级管理员账号");
            }
        }else if (!redisTemplate.hasKey(registerCode)) {
            //判断邀请码是否有效
            throw new OAException("不存在这个激活码");
        } else {
            int userId = Integer.parseInt(redisTemplate.opsForValue().get(registerCode).toString());
            //把当前用户绑定到ROOT帐户
//            User entity = new User();
            String openId = getOpenId(code);
            HashMap param = new HashMap();
            param.put("openId", openId);
            param.put("nickname", nickname);
            param.put("photo", photo);
            param.put("userId", userId);
            int row = userMapper.activeUserAccount(param);
            if (row != 1) {
                throw new OAException("账号激活失败");
            }
            redisTemplate.delete(registerCode);
            return userId;
        }
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        return userMapper.searchUserPermissions(userId);
    }

    @Override
    public Integer login(String code) {
        String openId = getOpenId(code);
        Integer id = userMapper.searchIdByOpenId(openId);
        if (id==null){
            throw new OAException("账户不存在");
        }
        //从消息队列接收消息，返回登陆
//        messageTask.receivedAsync(id + "");
        return id;
    }

    @Override
    public User searchById(int userId) {
        return userMapper.searchById(userId);
    }

    @Override
    public String searchUserHiredate(int userId) {
        return userMapper.searchUserHiredate(userId);
    }

    @Override
    public HashMap searchUserDept(int userId) {
        return userMapper.searchNameDept(userId);
    }

    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        ArrayList<HashMap> users = userMapper.searchUserGroupByDept(keyword);
        ArrayList<HashMap> depts = deptMapper.searchDeptMembers(keyword);
        for (HashMap dept :depts) {
            long deptId =(Long) dept.get("id");
            ArrayList members=new ArrayList<>();
            for (HashMap user :users){
                long id =(Long) user.get("deptId");
                if (deptId==id){
                    members.add(user);
                }
            }
            dept.put("members", members);
        }
        return depts;
    }

    @Override
    public ArrayList<HashMap> searchMembers(List param) {
        return userMapper.searchMembers(param);
    }

    @Override
    public List<HashMap> selectUserPhotoAndName(List param) {

        return userMapper.selectUserPhotoAndName(param);
    }

    @Override
    public JSONObject searchUserContactList() {
        ArrayList<HashMap> list = userMapper.searchUserContactList();
        String letter = null;
        JSONObject json = new JSONObject(true);
        JSONArray array = null;
        for (HashMap<String, String> map : list) {
            String name = map.get("name");
            String firstLetter = PinyinUtil.getPinyin(name).charAt(0) + "";
            firstLetter = firstLetter.toUpperCase();
            if (letter == null || !letter.equals(firstLetter)) {
                letter = firstLetter;
                array = new JSONArray();
                json.set(letter, array);
            }
            array.put(map);
        }
        return json;
    }

    @Override
    public HashMap searchUserInof(int userId) {
        return userMapper.searchUserInfo(userId);
    }

    @Override
    public void insertUser(HashMap param) {
        //保存记录
        int row = userMapper.insertUser(param);
        if (row == 1) {
            String email = (String) param.get("email");
            //根据Email查找新添加用户的主键值
            int userId = userMapper.searchUserIdByEmail(email);
            //生成激活码，并且用邮件发送
            activeCodeTask.sendActiveCodeAsync(userId, email);
        } else {
            throw new OAException("员工数据添加失败");
        }
    }

    @Override
    public int updateUserInfo(HashMap param) {
        int row = userMapper.updateUserInfo(param);
        if (row==1){
            Integer userId = (Integer) param.get("userId");
            String msg="你的个人资料已被修改成功";
            MessageEntity entity=new MessageEntity();
            entity.setSenderId(0);
            entity.setSenderPhoto("http://106.55.106.108/photo.jpg");
            entity.setSenderName("系统消息");
            entity.setMsg(msg);
            entity.setSendTime(new Date());
            messageTask.sendAsync(userId.toString(),entity);
        }
        return row;
    }

    @Override
    public void deleteUserById(int id) {
        int row = userMapper.deleteUserById(id);
        if (row != 1) {
            throw new OAException("删除失败");
        }
        checkinMapper.deleteUserCheckin(id);
        messageMapper.deleteUserMessage(id);
        refMapper.deleteUserMessageRef(id);
        faceModelMapper.deleteFaceModel(id);
        messageTask.deleteQueue(id+"");
    }
}




